package com.agricultural.environment;

import com.agricultural.observer.EnvironmentObserver;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class EnvironmentMonitor {
    private double temperature;
    private double humidity;
    private double soilPH;
    private List<EnvironmentObserver> observers = new ArrayList<>();
    private Random random = new Random();
    private boolean monitoring = false;

    public void addObserver(EnvironmentObserver observer) {
        observers.add(observer);
    }

    public void removeObserver(EnvironmentObserver observer) {
        observers.remove(observer);
    }

    public void startMonitoring() {
        System.out.println("startMonitoring方法被调用");
        monitoring = true;
        System.out.println("开始环境监测...");
        // 模拟环境数据变化的线程
        Thread monitorThread = new Thread(() -> {
            while (monitoring) {
                updateEnvironmentData();
                try {
                    Thread.sleep(6000); // 每6秒更新一次数据
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("环境监测线程被中断");
                }
            }
        });
        monitorThread.setDaemon(true);
        monitorThread.start();
    }

    public void stopMonitoring() {
        monitoring = false;
        System.out.println("停止环境监测");
    }

    private void updateEnvironmentData() {
        // 模拟环境数据变化
        temperature = 20 + random.nextDouble() * 15;
        humidity = 40 + random.nextDouble() * 50;
        soilPH = 5 + random.nextDouble() * 3;
        
        notifyObservers("温度: " + temperature + "°C, 湿度: " + humidity + "%, 土壤pH值: " + soilPH);
    }

    private void notifyObservers(String message) {
        for (EnvironmentObserver observer : observers) {
            observer.update(this, message);
        }
    }

    public double getTemperature() {
        return temperature;
    }

    public double getHumidity() {
        return humidity;
    }

    public double getSoilPH() {
        return soilPH;
    }
}    